import json
import os
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from modules import scripts

from scripts.file_utils import read_file_as_json
from scripts.zj_data_loader import load_prompt

# prompt 所在目录
PROMPT_DIR = os.path.join(scripts.basedir(), "prompt")


def add_prompt(data):
    source_file_name = data['path']['pathArr'][0]
    source_file_path = os.path.join(PROMPT_DIR, source_file_name + '.json')

    source_data = read_file_as_json(source_file_path)
    cur_data = source_data
    index_arr = data['path']['indexArr']
    # 找到需要插入的节点
    for i in range(1, len(index_arr)):
        cur_data = cur_data[index_arr[i]]['subData']

    if data['type'] == 'save':
        cur_data['subData'].append({
            'name': data['tagName'],
            "positivePrompt": data['positivePrompt'],
            "negativePrompt": data['negativePrompt'],
            "parameters": data['parameters']
        })
    elif data['type'] == 'sub':
        cur_data['subData'].append({
            'name': data['subName'],
            'subData': [
                {
                    "name": data['tagName'],
                    "positivePrompt": data['positivePrompt'],
                    "negativePrompt": data['negativePrompt'],
                    "parameters": data['parameters']
                }
            ]
        })
    # 将 JSON 数据写入源文件 'tags.json' 中，以 UTF-8 编码格式
    with open(source_file_path, 'w', encoding='utf-8') as file:
        file.write(json.dumps(source_data, indent=2, ensure_ascii=False))
    load_prompt()


class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        request_data = json.loads(post_data)
        if self.path == '/zj-api/add-prompt':
            add_prompt(request_data)
        elif self.path == '/zj-api/add-config':
            # update_config(request_data)
            print(request_data)
        else:
            # 处理未知路径的POST请求，返回404 Not Found
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'404 Not Found')
            return

        # 假设我们将收到的数据直接作为响应返回给前端
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        # 解决跨域
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        # 返回数据到前端
        self.wfile.write(json.dumps(request_data).encode())

    def do_OPTIONS(self):
        # 处理CORS预检请求
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST')
        self.send_header('Access-Control-Allow-Headers', 'Content-type')
        self.end_headers()


def run_http():
    host = 'localhost'
    port = 7861
    server_address = (host, port)
    httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
    httpd.serve_forever()


def run_server():
    # 创建一个线程来运行HTTP服务器
    http_thread = threading.Thread(target=run_http)
    http_thread.daemon = True
    http_thread.start()
